//
//  ContactViewController.m
//  WeChat
//
//  Created by wangcarl on 16/8/31.
//  Copyright © 2016年 wangcarl. All rights reserved.
//

#import "ContactViewController.h"
#import "ChatViewController.h"

@interface ContactViewController ()
@property (strong,nonatomic) NSArray *users;
@end

@implementation ContactViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
   NSManagedObjectContext *rosterContext=   [XMPPTool sharedXMPPTool].rosterStorage.mainThreadManagedObjectContext;
    NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"XMPPUserCoreDataStorageObject"];
    NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:@"displayName" ascending:YES];
    request.sortDescriptors=@[sort];
    NSPredicate *pre=[NSPredicate predicateWithFormat:@"subscription !=%@",@"none"];
    request.predicate=pre;
    
    
    
    NSError *error=nil;
    NSArray *users=[rosterContext  executeFetchRequest:request error:&error];
    NSLog(@"%@",users);
    self.users=users;
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.users.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellreuse=@"ContactCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellreuse];
   XMPPUserCoreDataStorageObject *user= self.users[indexPath.row];
    cell.textLabel.text=user.displayName;
//    user.sectionNum
    
    NSLog(@"%@,%@",user.displayName,user.sectionNum);
    
    //KVO很便捷啊
    [user addObserver:self forKeyPath:@"sectionNum" options:NSKeyValueObservingOptionNew context:nil];
    
    
    switch ([user.sectionNum integerValue]) {
        case 0:
            cell.detailTextLabel.text=@"在线";
            break;
        case 1:
            cell.detailTextLabel.text=@"离开";
            break;
        case 2:
            cell.detailTextLabel.text=@"离线";
            break;
  
        default:
            cell.detailTextLabel.text=@"你猜";

            break;
    }
    
    if (user.photo) {
        cell.imageView.image=user.photo;
    }else{
       NSData *imageData= [[XMPPTool sharedXMPPTool].avatar photoDataForJID:user.jid];
        cell.imageView.image=[UIImage imageWithData:imageData];
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSegueWithIdentifier:@"toChatSegue" sender:nil];
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    [self.tableView reloadData];
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
     XMPPUserCoreDataStorageObject *user= self.users[indexPath.row];
    
    if (editingStyle==UITableViewCellEditingStyleDelete) {
        [[XMPPTool sharedXMPPTool].roster removeUser:user.jid];
    }
    
    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    

    [self performSegueWithIdentifier:@"toChatSegue" sender:user.jid];
    
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    id destVc=segue.destinationViewController;
    if ([destVc isKindOfClass:[ChatViewController class]]) {
        ChatViewController *chatVC=destVc;
        chatVC.friendJid=sender;
    }
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
